import React, { Component } from 'react';
import { connect } from 'dva';
import Ellipsis from '@/components/Ellipsis';
import { NAME_RULE, CODE_RULE } from '@/Constants/rules';
import { Menu, Dropdown, Icon, Form, Modal, Input, message } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import MyIcon from '@/components/MyIcon';
import { trim } from '@/utils/utils';
import styles from './UserGroups.less';
import Content from './Content';
import api from '@/api';

const FormItem = Form.Item;

@connect(({ usergroups, loading }) => ({
  sysRoots: usergroups.sysRoots,
  userGroupsMenuList: usergroups.userGroupsMenuList,
  createLoading: loading.effects['usergroups/createUserGroups'],
  updateLoading: loading.effects['usergroups/updateUserGroups']
}))
@Form.create()
class UserGroups extends Component {
  state = {
    currentSys: {},
    currentRootId: '',
    modalVisible: false,
    userGroupsAction: '',
  };
  menuRef = React.createRef();

  // 校验用户组名称唯一性
  checkNameUnique = (rule, value = '', callback) => {
    const { currentRootId, userGroupsAction, currentSys } = this.state;
    if (value == '') {
      return callback();
    }
    this.NameTimer && clearTimeout(this.NameTimer);
    this.NameTimer = setTimeout(() => {
      let payload = {};
      if (userGroupsAction === 'create') {
        payload = {
          rootId: currentSys.id,
          parentId: '0',
          id: '0',
        };
      } else {
        payload = {
          rootId: currentSys.id,
          parentId: '0',
          id: currentRootId,
        };
      }
      api.usergroups
        .checkNameUnique({
          pathParams: payload,
          queryParams: {
            [rule.field]: value,
          },
        })
        .then(res => {
          if (!res.data) {
            callback(rule.message);
          } else {
            callback();
          }
        });
    }, 500);
  };

  checkCodeUnique = (rule, value = '', callback) => {
    const { currentRootId, userGroupsAction, currentSys } = this.state;
    if (value == '') {
      return callback();
    }
    this.codeTimer && clearTimeout(this.codeTimer);
    this.codeTimer = setTimeout(() => {
      let payload = {};
      if (userGroupsAction === 'create') {
        payload = {
          rootId: currentSys.id,
          id: '0',
        };
      } else {
        payload = {
          rootId: currentSys.id,
          id: currentRootId,
        };
      }
      api.usergroups
        .checkCodeUnique({
          pathParams: payload,
          queryParams: {
            [rule.field]: value,
          },
        })
        .then(res => {
          if (!res.data) {
            callback(rule.message);
          } else {
            callback();
          }
        });
    }, 500);
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'usergroups/fetchSysRoots' }).then(res => {
      const { sysRoots } = this.props;
      if (sysRoots[0]) {
        this.fetchUserGroupsMenuList(sysRoots[0].id).then(res => {
          const { userGroupsMenuList } = this.props;
          const rootId = (userGroupsMenuList[0] || {}).id;
          this.setState({
            currentRootId: rootId,
          });
          rootId && this.fetchUserGroupsList({ id: rootId });
        });
        this.setState({
          currentSys: sysRoots[0],
        });
      }
    });
  }

  componentWillUnmount() {
    clearTimeout(this.NameTimer);
    clearTimeout(this.codeTimer);
  }

  scrollMenu = y => {
    this.menuRef.current.children[0].scrollTo(0, y);
  };

  // 获取用户组菜单
  fetchUserGroupsMenuList = rootId => {
    const { dispatch } = this.props;
    return dispatch({
      type: 'usergroups/fetchUserGroupsMenuList',
      payload: {
        pathParams: {
          rootId,
        },
      },
    });
  };
  // 获取用户组菜单
  fetchUserGroupsList = ({ id = '', pageIndex = 1, pageSize = 50, ...rest } = {}) => {
    const { dispatch } = this.props;
    let payload = {
      pageIndex,
      pageSize,
      ...rest,
    };
    return dispatch({
      type: 'usergroups/fetchUserGroupsList',
      payload: {
        queryParams: payload,
        pathParams: {
          id,
        },
      },
    });
  };

  initUserList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'usergroups/saveUserList',
      payload: {
        list: [],
        pagination: {},
      },
    });
  };

  // 添加用户组模态框取消按钮
  handleModalVisible = () => {
    this.setState({
      modalVisible: false,
    });
  };

  // 添加用户组保存按钮
  okHandle = () => {
    const { form, dispatch } = this.props;
    const { currentRootId, currentSys, userGroupsAction } = this.state;
    form.validateFields(async (err, fieldsValue) => {
      if (err) return;
      let res;
      if (userGroupsAction === 'create') {
        res = await dispatch({
          type: 'usergroups/createUserGroups',
          payload: {
            data: {
              rootId: currentSys.id,
              ...fieldsValue,
            },
          },
        });
        await this.fetchUserGroupsMenuList(currentSys.id);
        const { userGroupsMenuList } = this.props;
        this.scrollMenu(9999);
        this.handleMenuClick({
          key: userGroupsMenuList[userGroupsMenuList.length - 1].id,
        });
      } else {
        res = await dispatch({
          type: 'usergroups/updateUserGroups',
          payload: {
            data: {
              id: currentRootId,
              ...fieldsValue,
            },
          },
        });
      }
      if (res.errorCode === 0) {
        message.success(userGroupsAction === 'create' ? '添加成功' : '修改成功');
      }
      this.setState({
        modalVisible: false,
      });
    });
  };

  // 删除用户组
  deleteUserGroups = () => {
    const { dispatch } = this.props;
    const { currentRootId, currentSys } = this.state;
    Modal.confirm({
      title: '删除',
      content: '确定删除所选用户组吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        let delRes = await dispatch({
          type: 'usergroups/deleteUserGroups',
          payload: {
            pathParams: {
              id: currentRootId,
            },
          },
        });

        if (delRes.errorCode !== 0) return;

        await this.fetchUserGroupsMenuList(currentSys.id);
        message.success('删除成功');
        const { userGroupsMenuList } = this.props;
        if (userGroupsMenuList.length > 0) {
          this.handleMenuClick({ key: userGroupsMenuList[0].id });
          this.scrollMenu(0);
        } else {
          this.setState({ currentRootId: '' });
          dispatch({
            type: 'usergroups/saveUserList',
            payload: {
              list: [],
              pagination: {},
            },
          });
        }
      },
    });
  };

  // 编辑用户组
  modifyUserGroups = () => {
    this.setState({
      modalVisible: true,
      userGroupsAction: 'modify',
    });
  };

  // 新增用户组
  createUserGroups = () => {
    this.setState({
      modalVisible: true,
      userGroupsAction: 'create',
    });
  };

  // 切换系统
  switchSystem = e => {
    const { dispatch, sysRoots } = this.props;
    this.setState({
      currentSys: sysRoots.find(sys => sys.id === e.key) || {},
    });
    dispatch({
      type: 'usergroups/fetchUserGroupsMenuList',
      payload: {
        pathParams: {
          rootId: e.key,
        },
      },
    }).then(res => {
      const { userGroupsMenuList } = this.props;
      const rootId = (userGroupsMenuList[0] || {}).id;
      this.setState({
        currentRootId: rootId,
      });
      if (rootId) {
        this.fetchUserGroupsList({ id: rootId });
      } else {
        this.initUserList();
      }
    });
  };

  // 用户组菜单点击删除/修改
  handleSubMenuClick = e => {
    e.domEvent.stopPropagation();
    e.key === '1' ? this.deleteUserGroups() : this.modifyUserGroups();
  };

  // 用户组菜单点击
  handleMenuClick = e => {
    this.setState({
      currentRootId: e.key,
    });
    this.fetchUserGroupsList({ id: e.key });
  };

  handleOnInput = e => {
    window.compositionend && (e.target.value = trim(e.target.value));
  };

  render() {
    const { sysRoots, userGroupsMenuList, form, createLoading, updateLoading } = this.props;
    const { modalVisible, currentSys, userGroupsAction, currentRootId } = this.state;
    const currentUser = userGroupsMenuList.find(user => user.id === currentRootId) || {};
    const actionMenu = (
      <Menu onClick={this.handleSubMenuClick}>
        <Menu.Item key="0">
          <Icon type="edit" />
          &nbsp;编辑
        </Menu.Item>
        <Menu.Item key="1">
          <Icon type="delete" />
          &nbsp;删除
        </Menu.Item>
      </Menu>
    );

    const sysMenu = (
      <Menu onClick={this.switchSystem}>
        {(sysRoots || []).map(item => {
          return <Menu.Item key={item.id}>{item.name}</Menu.Item>;
        })}
      </Menu>
    );

    const userGroupsMenu = (
      <Menu
        className={styles.menu}
        selectedKeys={[this.state.currentRootId]}
        onClick={this.handleMenuClick}
        mode="inline"
      >
        {(userGroupsMenuList || []).map(role => {
          return (
            role.isSystem && 
            <Menu.Item key={role.id} className={styles.menuItem}>
              <span>
                <MyIcon className={styles.myIcon} type="iconoss---yonghuzu" />
                <Ellipsis tooltip length={10} className={styles.ellipsis}>
                  {role.name}
                </Ellipsis>
              </span>
              {/* {!role.isSystem && (
                <Dropdown
                  className={styles.showEllipsis}
                  key={role.id}
                  overlay={actionMenu}
                  trigger={['click']}
                  placement="bottomLeft"
                >
                  <Icon type="ellipsis" />
                </Dropdown>
              )} */}
            </Menu.Item>
          );
        })}
      </Menu>
    );

    return (
      <PageHeaderWrapper title="用户组管理">
        <div className={styles.main}>
          <div className={styles.leftmenu}>
            <div className={styles.menuTop}>
              <Dropdown overlay={sysMenu} trigger={['click']} placement="bottomLeft">
                <div className={styles.select}>
                  {currentSys.name}
                  &nbsp;&nbsp;
                  <Icon type="down" />
                </div>
              </Dropdown>
              {/* <div>
                <Icon
                  type="plus-circle"
                  onClick={this.createUserGroups}
                  style={{
                    fontSize: '18px',
                    marginRight: '5px',
                    marginTop: '5px',
                    color: '#1890FF',
                  }}
                />
              </div> */}
            </div>
            <div ref={this.menuRef}>{userGroupsMenu}</div>
          </div>
          <div style={{ display: currentRootId ? 'block' : 'none' }} className={styles.right}>
            <Content currentRootId={currentRootId} />
          </div>
        </div>
        <Modal
          maskClosable={false}
          keyboard={false}
          destroyOnClose
          title={userGroupsAction === 'create' ? '添加用户组' : '编辑用户组'}
          visible={modalVisible}
          confirmLoading={createLoading || updateLoading}
          onOk={this.okHandle}
          onCancel={this.handleModalVisible}
        >
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="名称">
            {form.getFieldDecorator('name', {
              initialValue: userGroupsAction === 'modify' ? currentUser.name : '',
              rules: [
                { required: true, message: '名称不能为空', whitespace: true },
                { pattern: NAME_RULE.PATTERN, message: NAME_RULE.MESSAGE },
                { validator: this.checkNameUnique, message: '名称已存在' },
              ],
            })(<Input onInput={this.handleOnInput} maxLength={30} />)}
          </FormItem>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="编码">
            {form.getFieldDecorator('code', {
              initialValue: userGroupsAction === 'modify' ? currentUser.code : '',
              rules: [
                { required: true, message: '编码不能为空', whitespace: true },
                { pattern: CODE_RULE.PATTERN, message: CODE_RULE.MESSAGE },
                { validator: this.checkCodeUnique, message: '编码已存在' },
              ],
            })(
              <Input
                onInput={this.handleOnInput}
                maxLength={15}
                disabled={userGroupsAction === 'modify'}
              />
            )}
          </FormItem>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default UserGroups;
